package main

import (
	"flag"
	"fmt"
	"net/http"
	"strings"

	"server/internal/config"
	"server/internal/handler"
	"server/internal/svc"
	"server/queue"

	"github.com/zeromicro/go-zero/core/conf"
	"github.com/zeromicro/go-zero/core/service"
	"github.com/zeromicro/go-zero/rest"
)

var configFile = flag.String("f", "etc/server-api.yaml", "the config file")

func main() {
	flag.Parse()

	var c config.Config
	conf.MustLoad(*configFile, &c, conf.UseEnv())

	server := rest.MustNewServer(c.RestConf, rest.WithCustomCors(func(header http.Header) {
		header.Set("Access-Control-Allow-Origin", c.AllowOrigin)
		header.Add("Access-Control-Allow-Headers", "Authorization")
		header.Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
		header.Set("Access-Control-Expose-Headers", "Content-Length, Content-Type, Authorization")
	}, nil, c.AllowOrigin))

	if c.AllowOrigin == "" {
		server = rest.MustNewServer(c.RestConf)
	}
	defer server.Stop()

	ctx := svc.NewServiceContext(c)
	handler.RegisterHandlers(server, ctx)

	serviceGroup := service.NewServiceGroup()
	defer serviceGroup.Stop()
	platforms := strings.SplitSeq(c.Platform, ",")
	for platform := range platforms {
		if platform == "queue" {
			queueServers := queue.Start(ctx)
			for _, queueServer := range queueServers {
				serviceGroup.Add(queueServer)
			}
			continue
		}

		if platform == "web" {
			fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port)
			serviceGroup.Add(server)
			continue
		}
	}

	serviceGroup.Start()
}
